package dao;

import model.ParkingSpace;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ParkingSpaceDao {
    public void addParkingSpace(ParkingSpace ps) throws Exception {
        Connection conn = DBUtil.getConnection();
        String sql = "INSERT INTO parking_space (id, type, ownerId, renterId, fee) VALUES (?, ?, ?, ?, ?)";
        PreparedStatement pst = conn.prepareStatement(sql);
        pst.setInt(1, ps.getId());
        pst.setString(2, ps.getType());
        if (ps.getOwnerId() != null) pst.setInt(3, ps.getOwnerId()); else pst.setNull(3, Types.INTEGER);
        if (ps.getRenterId() != null) pst.setInt(4, ps.getRenterId()); else pst.setNull(4, Types.INTEGER);
        pst.setDouble(5, ps.getFee());
        pst.executeUpdate();
        pst.close();
        conn.close();
    }

    public List<ParkingSpace> getAllParkingSpaces() throws Exception {
        Connection conn = DBUtil.getConnection();
        String sql = "SELECT * FROM parking_space";
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery(sql);
        List<ParkingSpace> list = new ArrayList<>();
        while (rs.next()) {
            Integer ownerId = rs.getObject("ownerId") == null ? null : rs.getInt("ownerId");
            Integer renterId = rs.getObject("renterId") == null ? null : rs.getInt("renterId");
            list.add(new ParkingSpace(
                rs.getInt("id"),
                rs.getString("type"),
                ownerId,
                renterId,
                rs.getDouble("fee")
            ));
        }
        rs.close();
        st.close();
        conn.close();
        return list;
    }
}
